package com.intel.factorytest.activity;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Set;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.android.internal.telephony.ITelephony;

import com.intel.factorytest.R;
import com.intel.factorytest.cfparser.ConfigFileParseUtil;
import com.intel.factorytest.cfparser.concrete.AConfigFileParser;
import com.intel.factorytest.cfparser.concrete.PropertiesConfParser;
import com.intel.factorytest.util.PropertiesUtil;

import android.os.SystemProperties;

public class CallTest extends BaseActivity {
    private static final String TAG = "CallTest";
    private static final int REQ_CODE_CALL = 1;
    private static final String PHONENUMBER = "CallPhoneNumber";
    private static final String PHONENUMBER_DEF = "112";
    
    private static final int sRetryTimes = 3;
    private int retryCounter = 0;
    
    private TelephonyManager mTelephonyMgr;
    private TelephonyManager mSim2Telephony;
    private String mPhoneNumber = PHONENUMBER_DEF;
    
    private Button mCallBtn;
    private Button mSucBtn;
    // call timeout
    private int timeout = 2; // unit: sec
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.calltest);
        initView();
        
        mTelephonyMgr = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        
        if (isSystemTest) mPhoneNumber = getPhoneNumber();
        //call(mPhoneNumber);
        mItemTestFinish = true;//add by wangsm
    }
    
    @Override
    protected void initView() {
        mSucBtn = (Button) findViewById(R.id.success_button);        
        mSucBtn.setVisibility(View.INVISIBLE);
        
        mCallBtn = (Button) findViewById(R.id.calltest_button);
        mCallBtn.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                mCallBtn.setEnabled(false);
                call(mPhoneNumber);
            }
        });
        
        super.initView();
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        Log.d(TAG, "onStart");        
        mCallBtn.setEnabled(true);
        super.onStart();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        Log.d(TAG, "onResume");
        super.onResume();
        mSucBtn.setVisibility(View.VISIBLE);
    }
    
    private void call(String phoneNumber) {
//        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber));
//        // startActivity(intent);
//        startActivityForResult(intent, REQ_CODE_CALL);
//        Intent intent= new Intent();
//         intent.setAction("android.intent.action.CALL");
//         intent.addCategory("android.intent.category.DEFAULT");
//         intent.setData(Uri.parse("tel:" + phoneNumber));
//        public static final String SCHEME_TEL = "tel";
//        public static final String EXTRA_CALL_ORIGIN = "com.android.phone.CALL_ORIGIN";
        int mSim1State=mTelephonyMgr.getSimState();
        
        int mCallSim =0;
                
//        if (mCallSim==0)
//        {
//            Toast mToast = Toast.makeText(getApplicationContext(), "没有SIM卡",Toast.LENGTH_SHORT);
////            mToast.setGravity(Gravity.CENTER, 0, 0);
//            mToast.show();
//            return;
//        }
        
        Uri uri = Uri.fromParts("tel", phoneNumber, null);
        Log.e(TAG, "phoneNumber:"+phoneNumber);
        final Intent intent;
        
        intent = new Intent(Intent.ACTION_CALL_PRIVILEGED,uri);
        // startActivity(intent);
        startActivityForResult(intent, REQ_CODE_CALL);
        
    }
    
    private String getPhoneNumber() {
        PropertiesConfParser parser = (PropertiesConfParser) ConfigFileParseUtil.getConfParserConcrete(this, AConfigFileParser.EXTENSION_PROPERTISE);
        PropertiesUtil properties = parser.getProperties(isPcba);
        return  properties.getProperty(PHONENUMBER, PHONENUMBER_DEF);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG,"onActivityResult >>>> requestCode:" + requestCode + ",resultCode:" + resultCode);

        if (data != null) {
            Bundle bundle = data.getExtras();
            Set<String> set = bundle.keySet();
            Iterator<String> it = set.iterator();
            while (it.hasNext()) {
                String key = it.next();
                Log.d(TAG,"CallTest onActivityResult intent " + key + "=" + data.getExtra(key));
            }
        }
        // log end
        
        switch (requestCode) {
        case REQ_CODE_CALL:
            if (resultCode == RESULT_OK || resultCode == RESULT_CANCELED) is_pass = true;
            else is_pass = false;
            
            if (!is_pass) {// retry
                if (retryCounter < sRetryTimes) {
                    Log.d(TAG,"CallTest retry Call times=" + (++retryCounter));
                    call(mPhoneNumber);
                    retryCounter++;
                } else {
                    Log.d(TAG,"CallTest retry over!");
                    retryCounter = 0;
                    //finish();
                }
            } else {
                //finish();
                mSucBtn.setVisibility(View.VISIBLE);
            }
            
            break;

        default:
            break;
        }
    }
    
    @Override
    public void finish() {
        tc.setTestResult(is_pass);
        super.finish();
    }
    
    
    private void endCall(int afterSeconds) {
        if (afterSeconds < 0) afterSeconds = 1;
        
        Log.d(TAG,"CallTest enter endCall()");
        ITelephony iTelephony = getITelephony();
        Log.d(TAG,"CallTest itelephony=" + iTelephony);
        if (iTelephony != null) {
            while (afterSeconds > 0) {
                //Toast.makeText(getApplicationContext(), afterSeconds + "'s 后，通话将自动关闭！", Toast.LENGTH_SHORT).show(); // 有问题！！！
                Log.d(TAG,"CallTest " + afterSeconds + "'s 后，通话将自动关闭！");
                try {
                    Thread.sleep(1000);
                    afterSeconds--;
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            /*
            try {
                iTelephony.endCall();
                finish();
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            */
        } else {
            Log.d(TAG,"CallTest itelephony is null");
        }
    }
    
    private ITelephony getITelephony() {
        TelephonyManager mTelephonyManager = (TelephonyManager) this.getApplicationContext().getSystemService(TELEPHONY_SERVICE);
        Class<TelephonyManager> c = TelephonyManager.class;
        Method getITelephonyMethod = null;
        try {
            getITelephonyMethod = c.getDeclaredMethod("getITelephony", (Class[]) null);
            getITelephonyMethod.setAccessible(true);
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        ITelephony iTelephony = null;
        try {
            iTelephony = (ITelephony) getITelephonyMethod.invoke(mTelephonyManager, (Object[]) null);
            return iTelephony;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return iTelephony;
    }
}
